package com.scenic.userservice.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.scenic.common.bean.StrategyGuide;
import com.scenic.common.bean.RespBean;
import com.scenic.common.exception.ScenicSpotException;
import com.scenic.common.service.StrategyGuideService;
import com.scenic.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/strategy")
public class StrategyGuideController {
    @Autowired
    private StrategyGuideService strategyService;
    //添加 -- 攻略
    @PostMapping
    public RespBean insert(@RequestBody StrategyGuide strategyGuide,@RequestHeader("token") String token) throws ScenicSpotException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        if (strategyService.insert(strategyGuide) > 0) {
            return RespBean.ok("攻略添加成功");
        }
        return RespBean.error("攻略添加失败");
    }

    //根据id删除
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Long id, @RequestHeader("token") String token) throws ScenicSpotException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        if (!strategyService.delete(id, userId)) {
            return RespBean.ok("删除攻略失败");
        }

        return RespBean.ok("删除攻略成功");
    }
    @GetMapping("/{id}")
    //根据id查询攻略
    public RespBean selectById(@PathVariable("id") Long id) {

        StrategyGuide strategy = strategyService.selectById(id);
        return RespBean.ok("",strategy);

    }
    @GetMapping("/user")
    //根据id查询攻略
    public RespBean selectByUserId( @RequestHeader("token") String token, Integer pageNum, Integer pageSize) {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer)map.get("id");
        StrategyGuide condition = new StrategyGuide();
        condition.setUserId(userId);
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;
        PageHelper.startPage(pageNum, pageSize);
        List<StrategyGuide> strategyGuides = strategyService.selectByCondition(condition);
        PageInfo<StrategyGuide> pageInfo = new PageInfo<>(strategyGuides);
        return RespBean.ok("",pageInfo);
    }
    //条件分页搜索
    @GetMapping
    public RespBean selectByPage (StrategyGuide condition,Integer pageNum, Integer pageSize ) throws ScenicSpotException {
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        PageInfo<StrategyGuide> pageInfo = strategyService.selectByPage(pageNum, pageSize,condition);

        return RespBean.ok("",pageInfo);
    }
}
